import { SlateDescendant, SlateTransforms } from '@wangeditor/editor';
import { formatConfig } from './formatConfig';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';

interface htmlNode {
    content: string;
    style: {};
}

export const getFormattingDatas = (content: string) => {
    let lastValue: any = content || "";

    lastValue = lastValue.replaceAll("<br>", '\\n');

    const htmlToText = document.createElement('div');
    htmlToText.className = 'insert_HtmlToText';
    //特殊处理<br/> 改为一个空格 
    htmlToText.innerHTML = "<div>" + lastValue + "</div>";
    const htmlToTextNodex: any = htmlToText.childNodes;

    let formattingDatas: any = {};
    let keysIndex = 1;
    for (let index = 0; index <= htmlToTextNodex.length; index++) {
        if (htmlToTextNodex[index] && htmlToTextNodex[index].innerText) {
            let value = htmlToTextNodex[index].innerText;
            if (value && value.length > 0) {
                value = value.replace(/(\n)+/g, '~starHub_line_break~');
            }
            if (value && value.length > 0) {
                value.split('~starHub_line_break~').map(ivalue => {
                    formattingDatas["content_p" + keysIndex++] = ivalue;
                })
            }
        }
    }

    return JSON.stringify(formattingDatas);
}

export const convertNodesToFormatMap = (nodes: SlateDescendant[]) => {

    const result: Record<string, string> = {};
    if (!nodes || nodes.length === 0) {
        return result;
    }
    nodes.forEach((item, index) => {
        const { type, children } = item as { type: string, children: { text: string }[] };
        const text = children.map(textItem => textItem.text).join("")
        if (type.startsWith("header") || type.startsWith("paragraph")) {
            result[`odoc_p${index + 1}`] = text;
        }
    });
    return result;
}

/**
 * 从格式响应中提取格式映射信息
 * @param messageResponse 格式化接口返回的message字符串
 * @returns 解析后的格式映射对象，键为格式类型，值为对应的段落ID数组
 */
export const parseFormatResponseMessage = (messageResponse: string): Record<string, string[]> => {
    try {
        // 提取JSON字符串，处理markdown格式
        /*const jsonMatch = messageResponse.match(/```json\s*([\s\S]*?)\s*```/);
        if (!jsonMatch || !jsonMatch[1]) {
            throw new Error('无法解析格式化响应');
        }*/

        const jsonString = (messageResponse as any)?.replaceAll('```', '')?.replace('json\n', '');
        // 解析JSON字符串
        const formatMapping = JSON.parse(jsonString);
        return formatMapping;
    } catch (error) {
        console.error('解析格式响应失败:', error);
        return {};
    }
}

/**
 * 获取格式类型对应的样式
 * @param formatType 格式类型，如"正文"、"标题"等
 * @param docType 文档类型，bg-报告，tz-通知
 * @returns 样式对象
 */
export const getFormatTypeStyle = (formatType: string, docType: 'bg' | 'tz' = 'bg'): Record<string, string> => {
    try {
        // 获取指定格式类型的样式
        return formatConfig[docType][formatType];
    } catch (error) {
        console.error('获取格式样式失败:', error);
        return null;
    }
}

/**
 * 应用格式化样式到编辑器内容
 * @param editor wangEditor实例
 * @param formatResponse 格式化接口返回的响应
 * @param docType 文档类型，bg-报告，tz-通知
 * @returns 是否成功应用样式
 */
export const applyFormatToEditor = (editor: any, formatResponse: string, docType: 'bg' | 'tz' = 'bg'): boolean => {
    try {
        if (!editor) {
            throw new Error('编辑器实例不存在');
        }

        // 解析格式响应
        const formatMapping = parseFormatResponseMessage(formatResponse);
        if (Object.keys(formatMapping).length === 0) {
            throw new Error('格式映射为空');
        }

        // 检查编辑器是否有children属性
        if (!editor.children || !Array.isArray(editor.children)) {
            throw new Error('编辑器内容结构无效，无法获取内容节点');
        }

        // 获取所有段落节点
        const nodes = editor.children;

        if (nodes.length === 0) {
            throw new Error('编辑器中没有找到段落节点');
        }
        // 遍历格式映射，为每个段落应用样式
        Object.entries(formatMapping).forEach(([formatType, paragraphIds]) => {
            // 获取该格式类型的样式
            const style = getFormatTypeStyle(formatType, docType);

            // 遍历该格式类型下的所有段落ID
            paragraphIds.forEach(paragraphId => {
                // 从ID中提取索引，例如odoc_p1中的1
                const paragraphIndex = parseInt(paragraphId.replace('odoc_p', ''), 10);
                if (isNaN(paragraphIndex) || paragraphIndex <= 0 || paragraphIndex > nodes.length) {
                    console.warn(`段落索引 ${paragraphIndex} 超出范围或无效`, paragraphId);
                    return;
                }

                // 获取对应的段落元素（索引从0开始，所以要减1）
                const node = nodes[paragraphIndex - 1];
                if (!node) {
                    console.warn(`未找到索引为 ${paragraphIndex} 的段落节点`);
                    return;
                }
                try {
                    // 使用slate.js的Transform API来修改节点属性
                    // 首先获取当前节点的路径
                    // const path = editor.children.indexOf(node) !== -1
                    //     ? [editor.children.indexOf(node)]
                    //     : null;

                    // if (!path) {
                    //     console.warn(`无法确定段落 ${paragraphId} 在编辑器中的路径`,node);
                    //     return;
                    // }

                    const path = [(paragraphIndex - 1)]

                    // 准备要应用的节点属性
                    const nodeProps: Record<string, any> = {};

                    // 处理段落级别的样式
                    Object.entries(style).forEach(([styleKey, styleValue]) => {
                        // 跳过未设置的样式
                        if (styleValue === 'unset') return;

                        switch (styleKey) {
                            case 'text-align':
                                nodeProps.textAlign = styleValue;
                                break;
                            case 'text-indent':
                                nodeProps.indent = styleValue;
                                break;
                            case 'line-height':
                                nodeProps.lineHeight = styleValue;
                                break;
                            case 'margin-left':
                                nodeProps.marginLeft = styleValue;
                                break;
                        }
                    });

                    // 应用段落级样式
                    if (Object.keys(nodeProps).length > 0) {
                        try {
                            // 使用Transforms.setNodes来设置节点属性
                            editor.select({ anchor: { path: [...path, 0], offset: 0 }, focus: { path: [...path, 0], offset: 0 } });
                            SlateTransforms.setNodes(editor, nodeProps, { at: path });
                        } catch (err) {
                            console.error('应用段落属性失败:', err);
                        }
                    }

                    // 处理文本级别的样式
                    const textStyles: Record<string, any> = {};
                    Object.entries(style).forEach(([styleKey, styleValue]) => {
                        // 跳过未设置的样式
                        if (styleValue === 'unset') return;

                        switch (styleKey) {
                            case 'font-family':
                                textStyles.fontFamily = styleValue;
                                break;
                            case 'font-size':
                                textStyles.fontSize = styleValue;
                                break;
                            case 'color':
                                textStyles.color = styleValue;
                                break;
                            case 'font-weight':
                                if (styleValue === 'bold') {
                                    textStyles.bold = true;
                                }
                                break;
                            case 'font-style':
                                if (styleValue === 'italic') {
                                    textStyles.italic = true;
                                }
                                break;
                        }
                    });

                    // 应用文本级样式
                    if (Object.keys(textStyles).length > 0) {
                        try {
                            // 遍历段落中的所有文本节点，应用样式
                            for (let i = 0; i < node.children.length; i++) {
                                const textPath = [...path, i];
                                // 使用editor.addMark来设置文本样式
                                Object.entries(textStyles).forEach(([key, value]) => {
                                    editor.select({ anchor: { path: textPath, offset: node.children[i].text.length }, focus: { path: textPath, offset: 0 } });
                                    editor.addMark(key, value);
                                });
                            }
                        } catch (err) {
                            console.error('应用文本样式失败:', err);
                        }
                    }

                } catch (styleError) {
                    console.error(`应用样式到段落 ${paragraphId} 失败:`, styleError);
                }
            });
        });

        // 确保编辑器更新视图
        if (editor.onChange && typeof editor.onChange === 'function') {
            editor.onChange();
        }
        return true;
    } catch (error) {
        console.error('应用格式样式失败:', error);
        return false;
    }
}


export const htmlContentToEditor = (editor: any, formatResponse: [htmlNode]): boolean => {
    try {
        if (!editor) {
            throw new Error('编辑器实例不存在');
        }

        // 检查编辑器是否有children属性
        if (!editor.children || !Array.isArray(editor.children)) {
            throw new Error('编辑器内容结构无效，无法获取内容节点');
        }
        console.log(editor.children);
        editor.children.forEach((item: any, paragraphIndex) => {
            const { type, children } = item as { type: string, children: { text: string }[] };
            if (type.startsWith("header") || type.startsWith("paragraph")) {
                const text = children.map(textItem => textItem.text).join("")

                if(!text || text.length === 0) {
                    return;
                }

                let contentLength = 0;
                
                let _index = 0;
                let _style = {};
                text.split('-').filter(ivalue => !!ivalue).forEach((ivalue, index) => {
                    const { style, content } = formatResponse[ivalue];
                    const textStyles: Record<string, any> = {};
                    Object.entries(style).forEach(([styleKey, styleValue]) => {
                        // 跳过未设置的样式
                        if (styleValue === 'unset') return;

                        switch (styleKey) {
                            case 'font-family':
                                textStyles.fontFamily = styleValue;
                                break;
                            case 'font-size':
                                textStyles.fontSize = styleValue;
                                break;
                            case 'color':
                                textStyles.color = styleValue;
                                break;
                            case 'font-weight':
                                if (styleValue === 'bold') {
                                    textStyles.bold = true;
                                }
                                break;
                            case 'font-style':
                                if (styleValue === 'italic') {
                                    textStyles.italic = true;
                                }
                                break;
                        }
                    });
                    // 使用editor.addMark来设置文本样式
                    Object.entries(textStyles).forEach(([key, value]) => {
                        editor.select({ anchor: { path: [paragraphIndex, _index], offset: 0 }, focus: { path: [paragraphIndex, _index], offset: 33 } });
                        editor.addMark(key, value);
                    });
                    editor.insertText(content)
                    contentLength += content.length;

                    if(!deepEqual(_style, textStyles)){
                        _index++;
                        _style = textStyles;
                    }
                })
            }
        });

        // 确保编辑器更新视图
        if (editor.onChange && typeof editor.onChange === 'function') {
            editor.onChange();
        }
        
        return true;
    } catch (error) {
        console.error('应用格式样式失败:', error);
        return false;
    }
}

function deepEqual(a, b) {
    if (a === b) return true;
    
    if (a && b && typeof a === 'object' && typeof b === 'object') {
        // 数组比较
        if (Array.isArray(a) && Array.isArray(b)) {
            if (a.length !== b.length) return false;
            for (let i = a.length; i-- !== 0;) {
                if (!deepEqual(a[i], b[i])) return false;
            }
            return true;
        }
        
        // 对象比较
        const keys = Object.keys(a);
        if (keys.length !== Object.keys(b).length) return false;
        
        for (const key of keys) {
            if (!(key in b) || !deepEqual(a[key], b[key])) {
                return false;
            }
        }
        return true;
    }
    
    // NaN 比较
    return a !== a && b !== b;
}